#!/usr/bin/env python
# -*- coding: utf8 -*-

'''
# =======
# User: luwei
# Date: 11-4-21
# Time: 下午3:51
# email = luw2007@gmail.com
# =======
'''

# Imports
# =======
import os
import paramiko

def ssh2_connect(host, port, user, password):
    paramiko.util.log_to_file('ssh2.log')
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(host, port, user, password)
    stdin, stdout, stderr = s.exec_command('df')
    print stdout.read()
    s.close()

def ssh2_ftp_get(host, port, user, password, dir_path, local_path):
    #paramiko.util.log_to_file('ssh2.log')
    t = paramiko.Transport((host, port))
    t.connect(username=user, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    files = sftp.listdir(dir_path)
    local_files = os.listdir(local_path)
    for f in files:
        print 'Retrieving' ,os.path.join(dir_path,f)
        sftp.get(os.path.join(dir_path,f),os.path.join(local_path,f))
    t.close()

def ssh2_ftp_put(host, port, user, password, dir_path, local_path):
    #paramiko.util.log_to_file('ssh2.log')
    t = paramiko.Transport((host, port))
    t.connect(username=user, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    files = sftp.listdir(dir_path)
    local_files = os.listdir(local_path)
    for f in local_files:
        print 'putting' ,os.path.join(dir_path,f)
        sftp.put(os.path.join(local_path,f),os.path.join(dir_path,f))
    t.close()

def ssh2_ftp_lsr(host, port, user, password, dir_path):
    '''显示目录所有的文件及其子目录的文件'''
    #paramiko.util.log_to_file('ssh2.log')
    t = paramiko.Transport((host, port))
    t.connect(username=user, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    files = sftp.listdir(dir_path)
    for f in files:
        try:
            sftp.listdir(os.path.join(dir_path,f))
        except :
            print os.path.join(dir_path,f)
        else:
            print "D", os.path.join(dir_path,f)
            ssh2_ftp_ls(host, port, user, password, os.path.join(dir_path,f))
    t.close()

def ssh2_ftp_ls(host, port, user, password, dir_path):
    '''显示目录所有的文件及其子目录的文件'''
    #paramiko.util.log_to_file('ssh2.log')
    t = paramiko.Transport((host, port))
    t.connect(username=user, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    files = sftp.listdir(dir_path)
    for f in files:
        print os.path.join(dir_path,f)
    t.close()

def main():
    '''test main'''
    ssh2_connect("172.20.106.11",22,"root","xin**wang")
    ssh2_ftp_ls("172.20.106.11",22,"root","xin**wang","/home/osqa/osqa-server")
    #ssh2_ftp_put("172.20.106.11",22,"root","xin**wang","/root/9.27/","/tmp/testdir")
    print "done"

if __name__ == '__main__':
    main()